import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTime } from '@/utils/auth'
import router from '@/router'

const checkTime = () => {
  const now = new Date()
  const old = getTime()
  const duration = 1000 * 60 * 60 * 12
  return now - old > duration
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      // console.log(checkTime())
      if (checkTime()) {
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token 已超时'))
      } else {
        config.headers.Authorization = 'Bearer ' + token
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// response interceptor
service.interceptors.response.use(
  res => {
    const { success, message, data } = res.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
  },
  err => {
    console.dir(err)
    if (err.response && err.response.data && err.response.data.code === 10002) {
      Message.error(err.message)
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message.error(err.message)
    }
    return Promise.reject(err)
  }
)

export default service
